<?php
require_once("modules/exceptions/persistenceexception.class.php");
require_once("modules/debug.class.php");

class Persistence {
	private static $_instance;
	
	private $connection=null;
	
	
	function __construct($connection) {
		$this->connection = $connection;
	}
	
	/**
	 * retrieve all occurence for $entity.
	 * @param string $entity name of the entity to be retrieved.
	 * @return array of occurences : <code>array('concat_key_1'=>array(fields_1...)[,'concat_key_n'=>array(...),...])</code>
	 */
	public function findAll($entity=""){
		__debug(__FILE__,__LINE__,"Persistence::findAll() - find all $entity.");
		return $this->getManager($entity)->finAll();
	}
	
	/**
	 * retrieve the corresponding <code>$entity</code> manager.
	 * @param string $entity
	 * @return Entity inherited class.
	 */
	public function getManager($entity=""){
		$root=dirname($_SERVER['SCRIPT_FILENAME'])."/app/entities/";
		__debug(__FILE__,__LINE__,"load $entity manager : $root$entity.class.php");
		if(isset($entity) && $entity!="") {
			if(file_exists($root."$entity.class.php")){
				require($root."$entity.class.php");
			}
			$instance = new $entity;
			$instance->setConnection($this->connection);
			__debug(__FILE__,__LINE__,"instance: ".print_r($instance,true));
			return $instance;
		}else{
			throw new PersistenceException("Entity does not exists");
		}
	}

	/**
	 * return the static instance of the Persistence.
	 * create the instance if does not already exist.
	 */
	function getInstance($connection){
		if(!isset(self::$_instance)){
			self::$_instance = new Persistence($connection);
		}
		return self::$_instance;
	}

}?>